package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.liuzhilin.domain.Message;
import com.liuzhilin.service.MessageService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/emailPrint")
public class EmailPrint extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型为 JSON
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        // 获取请求参数
        String username = request.getParameter("username");
        String typeParam = request.getParameter("type");

        int type=Integer.parseInt(typeParam);

        // 调用服务层获取邮件列表
        List<Message> emails = MessageService.getMessage(username, type);

        // 将邮件信息转换为 JSON 格式，并返回给客户端
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.writeValue(response.getWriter(), emails);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
            e.printStackTrace();
        }
    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}

